﻿#include "criteria.h"


std::list<People> Criteria_Handsome::filter(std::list<People> filter_list)
{
    this->m_list.clear();

    for (People &p : filter_list)
    {
        if (p.appearance() == "handsome")
        {
            m_list.push_back(p);
        }
    }
    return m_list;
}

std::list<People> Criteria_Higher::filter(std::list<People> filter_list)
{
    this->m_list.clear();

    for (People &p : filter_list)
    {
        if (p.height() >= m_height_lower && p.height() <= m_height_higher)
        {
            m_list.push_back(p);
        }
    }
    return m_list;
}

std::list<People> Criteria_Age::filter(std::list<People> filter_list)
{
    this->m_list.clear();

    for (People &p : filter_list)
    {
        if (p.age() >= m_age_lower && p.age() <= m_age_higher)
        {
            m_list.push_back(p);
        }
    }
    return m_list;
}

std::list<People> Criteria_Weight::filter(std::list<People> filter_list)
{
    this->m_list.clear();

    for (People &p : filter_list)
    {
        if (p.weight() >= m_weight_lower && p.weight() <= m_weight_higher)
        {
            m_list.push_back(p);
        }
    }
    return m_list;
}

std::list<People> Criteria_SEX::filter(std::list<People> filter_list)
{
    this->m_list.clear();

    for (People &p : filter_list)
    {
        if (p.sex() == m_sex )
        {
            m_list.push_back(p);
        }
    }
    return m_list;
}

std::list<People> Or_Criteria::filter(std::list<People> filter_list)
{
    m_list.clear();
    for (std::shared_ptr<Criteria> &pCriteria : m_criteria_list)
    {
        m_list.merge(pCriteria->filter(filter_list));
    }
    // 过滤器会累积重复的对象，去重
    m_list.sort();
    // unique指向不重复序列的下一个对象
    m_list.erase(unique(m_list.begin(), m_list.end()), m_list.end());
    return m_list;
}


void Or_Criteria::add_criteria(std::shared_ptr<Criteria> criteria)
{
    if (criteria != nullptr)
    {
        m_criteria_list.push_back(criteria);
    }
}

std::list<People> And_Criteria::filter(std::list<People> filter_list)
{
    m_list = filter_list;

    // 使用迭代器iterator
//    std::list<std::shared_ptr<Criteria>>::iterator it;
//    for (it = m_criteria_list.begin(); it != m_criteria_list.end(); it++)
//    {
//        m_list = (*it)->filter(m_list);
//    }

    // 使用 for的C++11语法，比上面省一行代码,风格更简单
    for (std::shared_ptr<Criteria> &pCriteria : m_criteria_list)
    {
        m_list = pCriteria->filter(m_list);
    }
    return m_list;
}

void And_Criteria::add_criteria(std::shared_ptr<Criteria> criteria)
{
    if (criteria != nullptr)
    {
        m_criteria_list.push_back(criteria);
    }
}
